<script>
import axios from "../../axios/axiosHelper";
import { Plus, Search, Edit, Delete, Download } from '@element-plus/icons-vue';

export default {
  name: "BookResource",
  components: {
    Plus,
    Search,
    Edit,
    Delete,
    Download
  },
  data() {
    return {
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      searchForm: {
        field: '',
        code: ''
      },
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: '',
        book_id: '',
        type: '',
        url: '',
        description: ''
      },
      rules: {
        book_id: [
          { required: true, message: '请选择图书', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择资源类型', trigger: 'change' }
        ],
        url: [
          { required: true, message: '请输入资源链接', trigger: 'blur' },
          { min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }
        ]
      },
      bookList: [],
      resourceTypes: [
        { value: 'PDF', label: 'PDF文档' },
        { value: 'EPUB', label: 'EPUB电子书' },
        { value: 'AUDIO', label: '音频资源' },
        { value: 'VIDEO', label: '视频资源' },
        { value: 'IMAGE', label: '图片资源' },
        { value: 'OTHER', label: '其他资源' }
      ]
    };
  },
  created() {
    this.fetchData();
    this.fetchBookList();
  },
  methods: {
    // 获取图书资源数据
    fetchData() {
      this.loading = true;
      const params = {
        offset: (this.currentPage - 1) * this.pageSize,
        limit: this.pageSize
      };
      
      // 添加搜索条件
      if (this.searchForm.code) {
        params.code = this.searchForm.code;
      }
      
      axios.get('/book-resource/list', { params }).then(response => {
        this.tableData = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      }).catch(error => {
        console.error('获取图书资源数据失败:', error);
        this.$message.error('获取图书资源数据失败');
        this.loading = false;
      });
    },
    // 获取图书列表
    fetchBookList() {
      axios.get('/book/all').then(response => {
        this.bookList = response.data;
      }).catch(error => {
        console.error('获取图书列表失败:', error);
        this.$message.error('获取图书列表失败');
      });
    },
    // 处理页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchData();
    },
    // 打开添加对话框
    handleAdd() {
      this.dialogTitle = '添加图书资源';
      this.form = {
        id: '',
        book_id: '',
        type: '',
        url: '',
        description: ''
      };
      this.dialogVisible = true;
    },
    // 编辑图书资源
    handleEdit(index, row) {
      this.dialogTitle = '编辑图书资源';
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          const formData = {
            ...this.form
          };
          
          if (this.form.id) {
            // 更新
            axios.put('/book-resource/update', formData).then(response => {
              this.$message.success('更新成功');
              this.dialogVisible = false;
              this.fetchData();
              this.loading = false;
            }).catch(error => {
              console.error('更新图书资源失败:', error);
              this.$message.error('更新图书资源失败');
              this.loading = false;
            });
          } else {
            // 添加
            axios.post('/book-resource/add', formData).then(response => {
              this.$message.success('添加成功');
              this.dialogVisible = false;
              this.fetchData();
              this.loading = false;
            }).catch(error => {
              console.error('添加图书资源失败:', error);
              this.$message.error('添加图书资源失败');
              this.loading = false;
            });
          }
        } else {
          return false;
        }
      });
    },
    // 删除图书资源
    handleDelete(index, row) {
      this.$confirm('确认删除该图书资源?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        axios.delete(`/book-resource/delete/${row.id}`).then(response => {
          this.$message.success('删除成功');
          this.fetchData();
          this.loading = false;
        }).catch(error => {
          console.error('删除图书资源失败:', error);
          this.$message.error('删除图书资源失败');
          this.loading = false;
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 获取图书名称
    getBookName(bookId) {
      const book = this.bookList.find(item => item.id === bookId);
      return book ? book.name : bookId;
    },
    // 获取资源类型名称
    getResourceTypeName(type) {
      const resourceType = this.resourceTypes.find(item => item.value === type);
      return resourceType ? resourceType.label : type;
    },
    // 下载资源
    handleDownload(url) {
      if (!url) {
        this.$message.warning('资源链接不存在');
        return;
      }
      
      // 创建一个隐藏的a标签来触发下载
      const link = document.createElement('a');
      link.href = url;
      link.target = '_blank';
      link.download = url.substring(url.lastIndexOf('/') + 1);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }
}
</script>

<template>
  <div class="book-resource-container">
    <!-- 标题栏 -->
    <div class="header">
      <div class="title-section">
        <h2 class="page-title">图书资源管理</h2>
        <el-button type="primary" size="small" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加资源
        </el-button>
      </div>
      <div class="search">
        <el-input v-model="searchForm.code" placeholder="请输入关键词搜索..." clearable size="small" style="width: 250px;">
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" size="small" @click="fetchData">搜索</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        v-loading="loading"
        element-loading-text="加载中..."
        :header-cell-style="{backgroundColor: '#f5f7fa', color: '#606266'}"
        highlight-current-row
        stripe
      >
        <el-table-column type="index" min-width="5%" align="center" label="序号"></el-table-column>
        <el-table-column prop="id" label="ID" min-width="5%" align="center"></el-table-column>
        <el-table-column label="图书" min-width="15%" align="center">
          <template #default="scope">
            {{ getBookName(scope.row.book_id) }}
          </template>
        </el-table-column>
        <el-table-column label="资源类型" min-width="10%" align="center">
          <template #default="scope">
            {{ getResourceTypeName(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="url" label="资源链接" min-width="20%" align="center">
          <template #default="scope">
            <el-tooltip 
              :content="scope.row.url" 
              placement="top" 
              :hide-after="3000" 
              :show-after="500"
              effect="light"
              max-width="300"
            >
              <div class="url-ellipsis">{{ scope.row.url }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="20%" align="center">
          <template #default="scope">
            <el-tooltip 
              :content="scope.row.description" 
              placement="top" 
              :hide-after="3000" 
              :show-after="500"
              effect="light"
              max-width="300"
              v-if="scope.row.description"
            >
              <div class="description-ellipsis">{{ scope.row.description }}</div>
            </el-tooltip>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="25%" align="center">
          <template #default="scope">
            <div class="operation-buttons">
              <el-tooltip content="下载" placement="top" :hide-after="1500">
                <el-button type="success" circle size="small" @click="handleDownload(scope.row.url)">
                  <el-icon><Download /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="编辑" placement="top" :hide-after="1500">
                <el-button type="primary" circle size="small" @click="handleEdit(scope.$index, scope.row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" :hide-after="1500">
                <el-button type="danger" circle size="small" @click="handleDelete(scope.$index, scope.row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="550px" 
      :close-on-click-modal="false"
      destroy-on-close
      center
      class="custom-dialog"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="图书" prop="book_id">
          <el-select 
            v-model="form.book_id" 
            placeholder="请选择图书" 
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in bookList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资源类型" prop="type">
          <el-select 
            v-model="form.type" 
            placeholder="请选择资源类型" 
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in resourceTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资源链接" prop="url">
          <el-input 
            v-model="form.url" 
            placeholder="请输入资源链接"
            clearable
            maxlength="255"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入资源描述"
            maxlength="255"
            show-word-limit
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" plain>取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading" plain>确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.book-resource-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  display: flex;
  align-items: center;
}

.page-title {
  margin: 0;
  margin-right: 20px;
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  position: relative;
  padding-left: 10px;
}

.page-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 70%;
  width: 4px;
  background-color: #409eff;
  border-radius: 2px;
}

.search {
  display: flex;
  align-items: center;
}

.search .el-button {
  margin-left: 10px;
  transition: all 0.3s;
}

.search .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.table-container {
  flex: 1;
  overflow: auto;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.el-table {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
}

.el-table :deep(th.el-table__cell) {
  background-color: #f5f7fa;
  font-weight: 600;
}

.el-table :deep(tr:hover) {
  background-color: #f5f7fa;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.operation-buttons .el-button {
  transition: all 0.3s;
}

.operation-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.url-ellipsis,
.description-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

@media screen and (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search {
    margin-top: 15px;
    width: 100%;
  }
  
  .search .el-input {
    width: 100% !important;
  }
}

/* 自定义对话框样式 */
.custom-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.custom-dialog :deep(.el-dialog__header) {
  background-color: #f5f7fa;
  padding: 15px 20px;
  margin: 0;
  border-bottom: 1px solid #ebeef5;
}

.custom-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.custom-dialog :deep(.el-dialog__headerbtn) {
  top: 15px;
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 20px 25px;
}

.custom-dialog :deep(.el-dialog__footer) {
  padding: 10px 20px 15px;
  border-top: 1px solid #ebeef5;
}

.custom-dialog :deep(.el-form-item__label) {
  font-weight: 500;
}

.custom-dialog :deep(.el-input__inner),
.custom-dialog :deep(.el-textarea__inner) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: all 0.2s;
}

.custom-dialog :deep(.el-input__inner:focus),
.custom-dialog :deep(.el-textarea__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
</style>